<template>
  <div class="common-container">
    <!-- 页面标题和返回按钮 -->
    <div class="page-header">
      <el-page-header @back="goBack">
        <template #content>
          <span class="page-title">{{ datasetName }} - 字段管理</span>
        </template>
      </el-page-header>
    </div>

    <!-- 字段列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>字段列表</span>
          <div class="header-operations">
            <el-button type="primary" @click="syncFields" :loading="syncingFields">
              <el-icon><RefreshRight /></el-icon> 同步字段
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="fieldList"
        :loading="loading"
        border
        style="width: 100%"
        row-key="id"
        :expand-row-keys="expandedRowKeys"
        @expand-change="handleExpandChange"
      >
        <!-- 扩展列 -->
        <el-table-column type="expand">
          <template #default="{ row }">
            <div class="field-detail">
              <div class="detail-section">
                <div class="detail-header">字段描述</div>
                <div class="detail-content">
                  {{ row.description || '暂无描述' }}
                </div>
              </div>

              <div class="detail-section" v-if="row.constraints && row.constraints.length > 0">
                <div class="detail-header">约束条件</div>
                <el-tag
                  v-for="constraint in row.constraints"
                  :key="constraint"
                  class="constraint-tag"
                  type="info"
                >
                  {{ constraint }}
                </el-tag>
              </div>

              <div class="detail-section">
                <div class="detail-header">变更历史</div>
                <el-timeline v-if="row.changes && row.changes.length > 0">
                  <el-timeline-item
                    v-for="(change, index) in row.changes"
                    :key="index"
                    :timestamp="change.changeTime"
                    :type="change.changeType === 'create' ? 'primary' : (change.changeType === 'update' ? 'warning' : 'danger')"
                  >
                    <div class="change-content">
                      <strong>{{ getChangeTypeLabel(change.changeType) }}</strong>
                      <span v-if="change.changeDetail">{{ change.changeDetail }}</span>
                    </div>
                  </el-timeline-item>
                </el-timeline>
                <div v-else class="no-data">暂无变更历史</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <!-- 基础信息列 -->
        <el-table-column label="ID" prop="id" width="80" />
        <el-table-column label="字段名" prop="name" min-width="120" />
        <el-table-column label="显示名称" prop="displayName" min-width="120" />
        <el-table-column label="字段类型" prop="type" width="100">
          <template #default="{ row }">
            <el-tag :type="getFieldTypeTagType(row.type)">
              {{ getFieldTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="长度/精度" prop="length" width="100" />
        <el-table-column label="必填" prop="required" width="80">
          <template #default="{ row }">
            <el-tag :type="row.required ? 'danger' : 'info'" effect="plain">
              {{ row.required ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="主键" prop="primaryKey" width="80">
          <template #default="{ row }">
            <el-tag :type="row.primaryKey ? 'success' : 'info'" effect="plain">
              {{ row.primaryKey ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" prop="updateTime" width="180" />

        <!-- 操作列 -->
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">
              <el-icon><Edit /></el-icon> 编辑
            </el-button>
            <el-button type="info" link @click="handleViewHistory(row)">
              <el-icon><InfoFilled /></el-icon> 变更历史
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑字段对话框 -->
    <el-dialog
      title="编辑字段"
      v-model="dialogVisible"
      width="650px"
         :modal="true"
    :append-to-body="true"
    :lock-scroll="true"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        :disabled="formLoading"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="字段名" prop="name">
              <el-input v-model="formData.name" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="显示名称" prop="displayName">
              <el-input v-model="formData.displayName" placeholder="请输入显示名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="3"
                placeholder="请输入字段描述"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="必填" prop="required">
              <el-switch v-model="formData.required" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否隐藏" prop="hidden">
              <el-switch v-model="formData.hidden" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="formLoading">确认</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 变更历史详情对话框 -->
    <el-dialog
      title="字段变更历史"
      v-model="historyDialogVisible"
      width="800px"
    >
      <div v-if="selectedField" class="field-history-container">
        <div class="field-info">
          <strong>字段名：</strong>{{ selectedField.name }} ({{ selectedField.displayName || '无显示名' }})
        </div>

        <el-timeline v-if="fieldChanges.length > 0">
          <el-timeline-item
            v-for="(change, index) in fieldChanges"
            :key="index"
            :timestamp="change.changeTime"
            :type="change.changeType === 'create' ? 'primary' : (change.changeType === 'update' ? 'warning' : 'danger')"
          >
            <div class="history-card">
              <div class="change-title">
                <strong>{{ getChangeTypeLabel(change.changeType) }}</strong>
              </div>
              <div v-if="change.changeDetail" class="change-detail">
                {{ change.changeDetail }}
              </div>
              <div v-if="change.before || change.after" class="change-diff">
                <div v-if="change.before" class="change-before">
                  <strong>变更前：</strong>
                  <pre>{{ formatChangeDiff(change.before) }}</pre>
                </div>
                <div v-if="change.after" class="change-after">
                  <strong>变更后：</strong>
                  <pre>{{ formatChangeDiff(change.after) }}</pre>
                </div>
              </div>
              <div class="change-meta">
                <span>操作人：{{ change.operator || '系统' }}</span>
              </div>
            </div>
          </el-timeline-item>
        </el-timeline>
        <div v-else class="no-data">暂无变更历史</div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Edit,
  InfoFilled,
  RefreshRight
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useDataFieldStore, fieldTypeOptions } from '@/stores/dataField'
import { useDataSetStore } from '@/stores/dataSet'

// 定义组件名
defineOptions({
  name: 'DataFieldPage'
})

// 路由
const route = useRoute()
const router = useRouter()

// 获取dataset ID
const datasetId = computed(() => route.params.datasetId)

// 获取字段store和数据集store
const dataFieldStore = useDataFieldStore()
const dataSetStore = useDataSetStore()

// 数据集名称
const datasetName = ref('')

// 状态
const fieldList = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const formRef = ref(null)
const formLoading = ref(false)
const expandedRowKeys = ref([])
const syncingFields = ref(false)

// 变更历史相关
const historyDialogVisible = ref(false)
const selectedField = ref(null)
const fieldChanges = ref([])

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  displayName: '',
  description: '',
  required: false,
  hidden: false
})

// 表单校验规则
const formRules = {
  displayName: [
    { required: true, message: '请输入显示名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符之间', trigger: 'blur' }
  ]
}

// 获取字段类型标签样式
const getFieldTypeTagType = (type) => {
  const typeMap = {
    'int': 'success',
    'float': 'info',
    'string': 'warning',
    'datetime': 'danger',
    'boolean': 'primary',
    'json': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取字段类型标签文本
const getFieldTypeLabel = (type) => {
  const option = fieldTypeOptions.find(item => item.value === type)
  return option ? option.label : type
}

// 获取变更类型标签文本
const getChangeTypeLabel = (type) => {
  const typeMap = {
    'create': '字段创建',
    'update': '字段更新',
    'delete': '字段删除'
  }
  return typeMap[type] || type
}

// 格式化变更内容
const formatChangeDiff = (diff) => {
  if (typeof diff === 'object') {
    return JSON.stringify(diff, null, 2)
  }
  return diff
}

// 获取字段列表
const getFieldList = async () => {
  loading.value = true
  try {
    const dataset = await dataSetStore.getDatasetById(datasetId.value)
    if (dataset) {
      datasetName.value = dataset.name
    }

    const list = await dataFieldStore.getFieldsByDatasetId(datasetId.value)
    fieldList.value = list
  } catch (error) {
    console.error('获取字段列表失败', error)
    ElMessage.error('获取字段列表失败')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.push({ name: 'dataDataset' })
}

// 处理展开/收起
const handleExpandChange = (row, expandedRows) => {
  expandedRowKeys.value = expandedRows.map(item => item.id)

  // 如果是展开，则获取该字段的变更历史
  if (expandedRows.some(item => item.id === row.id)) {
    loadFieldChanges(row)
  }
}

// 加载字段变更历史
const loadFieldChanges = async (field) => {
  try {
    const changes = await dataFieldStore.getFieldChangeHistory(field.id)
    // 将变更历史添加到字段对象中
    field.changes = changes
  } catch (error) {
    console.error('获取字段变更历史失败', error)
    ElMessage.error('获取字段变更历史失败')
  }
}

// 同步字段
const syncFields = async () => {
  syncingFields.value = true
  try {
    await dataFieldStore.syncFields(datasetId.value)
    ElMessage.success('字段同步成功')
    getFieldList()
  } catch (error) {
    console.error('字段同步失败', error)
    ElMessage.error(`字段同步失败：${error.message || '未知错误'}`)
  } finally {
    syncingFields.value = false
  }
}

// 编辑字段
const handleEdit = (row) => {
  Object.keys(formData).forEach(key => {
    if (key in row) {
      formData[key] = row[key]
    }
  })
  dialogVisible.value = true
}

// 查看变更历史
const handleViewHistory = async (row) => {
  selectedField.value = row
  historyDialogVisible.value = true
  try {
    const changes = await dataFieldStore.getFieldChangeHistory(row.id)
    fieldChanges.value = changes
  } catch (error) {
    console.error('获取字段变更历史失败', error)
    ElMessage.error('获取字段变更历史失败')
    fieldChanges.value = []
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()
    formLoading.value = true

    // 复制表单数据
    const formDataCopy = {}
    Object.keys(formData).forEach(key => {
      formDataCopy[key] = formData[key]
    })

    await dataFieldStore.updateField(formData.id, formDataCopy)
    ElMessage.success('字段更新成功')

    dialogVisible.value = false
    getFieldList()
  } catch (error) {
    console.error('表单提交失败', error)
    ElMessage.error('表单提交失败：' + (error.message || '未知错误'))
  } finally {
    formLoading.value = false
  }
}

// 初始化
onMounted(() => {
  getFieldList()
})
</script>

<style scoped>
.page-header {
  margin-bottom: 16px;
}

.page-title {
  font-size: 18px;
  font-weight: bold;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-operations {
  display: flex;
  gap: 8px;
}

.field-detail {
  padding: 16px;
}

.detail-section {
  margin-bottom: 16px;
}

.detail-header {
  font-weight: bold;
  margin-bottom: 8px;
  color: var(--el-color-primary);
  font-size: 14px;
}

.detail-content {
  color: var(--el-text-color-regular);
  line-height: 1.5;
}

.constraint-tag {
  margin-right: 8px;
  margin-bottom: 8px;
}

.no-data {
  color: var(--el-text-color-secondary);
  font-style: italic;
}

.change-content {
  margin-bottom: 8px;
}

.field-history-container {
  padding: 8px;
}

.field-info {
  margin-bottom: 16px;
  padding: 8px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.history-card {
  padding: 12px;
  background-color: var(--el-fill-color-blank);
  border-radius: 4px;
  box-shadow: var(--el-box-shadow-lighter);
}

.change-title {
  margin-bottom: 8px;
}

.change-detail {
  margin-bottom: 8px;
  color: var(--el-text-color-regular);
}

.change-diff {
  margin-bottom: 8px;
  font-family: monospace;
  font-size: 12px;
}

.change-before {
  margin-bottom: 8px;
  padding: 8px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.change-after {
  padding: 8px;
  background-color: var(--el-fill-color-light);
  border-radius: 4px;
}

.change-meta {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
</style>
